package com.quantdo.apex.elasticjob.boot;

import com.dangdang.ddframe.job.config.JobCoreConfiguration;
import com.dangdang.ddframe.job.config.simple.SimpleJobConfiguration;
import com.dangdang.ddframe.job.lite.api.JobScheduler;
import com.dangdang.ddframe.job.lite.config.LiteJobConfiguration;
import com.dangdang.ddframe.job.reg.base.CoordinatorRegistryCenter;
import com.quantdo.apex.elasticjob.constant.JobConfigBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.validation.constraints.NotNull;

/**
 * @author chenkuan
 * @version v1.0
 * @desc Job任务管理 创建
 * @date 2019/12/11 011 11:10
 */
@Service
public class JobManage {

	private Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private CoordinatorRegistryCenter registryCenter;

	@Autowired
	private JobConfigBean config;

	/**
	 * 添加SimpleJob任务
	 *
	 * @param jobName                job服务BeanName
	 * @param cron                   定时表达式
	 * @param shardingTotalCount     任务总分片数
	 * @param jobParameter           作业参数
	 * @param shardingItemParameters 分片序列号参数(分片序列号和参数用等号分隔，多个键值对用逗号分隔分片序列号从0开始，不可大于或等于作业分片总数如：0=a,1=b,2=c)
	 * @param description            作业描述
	 */
	public void addSimpleJob(@NotNull String jobName, @NotNull String cron, @NotNull int shardingTotalCount, String jobParameter, String shardingItemParameters, String description) {
		// 定义作业核心配置
		JobCoreConfiguration simpleCoreConfig = JobCoreConfiguration.newBuilder(jobName, cron, shardingTotalCount).jobParameter(jobParameter).shardingItemParameters(shardingItemParameters).description(description).failover(config.getFailover()).misfire(config.getMisfire()).build();
		// 定义SIMPLE类型配置
		SimpleJobConfiguration simpleJobConfig = new SimpleJobConfiguration(simpleCoreConfig, SimpleJobHandle.class.getCanonicalName());
		// 定义Lite作业根配置
		LiteJobConfiguration simpleJobRootConfig = LiteJobConfiguration.newBuilder(simpleJobConfig).overwrite(config.getOverwrite()).disabled(config.getDisabled()).build();
		//创建任务
		new JobScheduler(registryCenter, simpleJobRootConfig).init();
		logger.debug("simpleJobName:{} 创建成功", jobName);
	}
}
